package cn.mysdp.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.TreeSet;

public class IpUtil {

    public static String fixLocalIp(String ip) {
        if("0:0:0:0:0:0:0:1".equals(ip)) {
            return "127.0.0.1";
        }
        return ip;
    }

    public static Set<String> getIpAddr(HttpServletRequest httpServletRequest) {
        Set<String> ipRet = new TreeSet<>();
        String ip = httpServletRequest.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        } else {
            addIp(ipRet, ip);
        }
        ip = httpServletRequest.getHeader("Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        } else {
            addIp(ipRet, ip);
        }
        ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        }else {
            addIp(ipRet, ip);
        }
        ip = httpServletRequest.getRemoteAddr();
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {

        }else{
            addIp(ipRet, ip);
        }
        return ipRet;
    }

    public static void addIp(Set<String> set, String ip) {
        String[] ips = ip.split(",");
        for(String _ip: ips) {
            _ip = _ip.trim();
            if (_ip != null && !_ip.isEmpty()) {
                set.add(fixLocalIp(_ip));
            }
        }
    }
}
